﻿
//Array.forEach implementation for IE support..
//https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (callback, thisArg) {
        var T, k;
        if (this == null) {
            throw new TypeError(" this is null or not defined");
        }
        var O = Object(this);
        var len = O.length >>> 0; // Hack to convert O.length to a UInt32
        if ({}.toString.call(callback) != "[object Function]") {
            throw new TypeError(callback + " is not a function");
        }
        if (thisArg) {
            T = thisArg;
        }
        k = 0;
        while (k < len) {
            var kValue;
            if (k in O) {
                kValue = O[k];
                callback.call(T, kValue, k, O);
            }
            k++;
        }
    };
}
//Array.forEach implementation for IE support..


var ComFunJS = {
    URL: "http://www.ldx178.com",//
    APIURL: function (action) {
        if (action.substring(0, 1) != "/") {
	            action = "/" + action;
		}
        return ComFunJS.URL + action;
    },
    FilePath: function (fileid, wh) { //文件路径
        fileid = fileid + "";
        if (fileid) {
            var url = ComFunJS.APIURL("/file/thum/") + fileid.split(',')[0];
            if (wh) {//缩略图,默认200*200，可以传宽高/200/200
                if (wh.substring(0, 1) == "/") {
                    url += wh;
                } else {
                    url += "/" + wh;
                }

            }
            return url;
        }
        else {
            return "";
        }
    },
    getQueryString: function (name, defauval) {//获取URL参数,如果获取不到，返回默认值，如果没有默认值，返回空格
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) { return unescape(decodeURI(r[2])); }
        else {
            return defauval || "";
        }
    },
    changeUrlArg: function (url, arg, val) { //替换url参数值，如没有则新增该参数
        var pattern = arg + '=([^&]*)';
        var replaceText = arg + '=' + val;
        return url.match(pattern) ? url.replace(eval('/(' + arg + '=)([^&]*)/gi'), replaceText) : (url.match('[\?]') ? url + '&' + replaceText : url + '?' + replaceText);
    },
    //格式化日期，format:格式，默认yyyy-MM-dd,date时间，默认当前时间
    getNowDate: function (format, date) {
        if (!format) {
            format = "yyyy-MM-dd";
        }

        var now = new Date();
        if (date) {
            now = new Date(Date.parse(date.replace(/-/g, '/')));
        }

        var year = now.getFullYear();       //年
        var month = now.getMonth() + 1;     //月
        var day = now.getDate();            //日
        var hh = now.getHours();
        var mm = now.getMinutes();
        var ss = now.getSeconds();

        var clock = year + "-";

        switch (format) {
            case "yyyy-MM-dd": {
                if (month < 10)
                    clock += "0";
                clock += month + "-";
                if (day < 10) {
                    clock += "0";
                }
                clock += day;
            }
                break;
            case "yyyy-MM": {
                if (month < 10)
                    clock += "0";
                clock += month;
            }
                break;

            case "yyyy-MM-dd HH:mm:ss": {
                if (month < 10)
                    clock += "0";
                clock += month + "-";
                if (day < 10) {
                    clock += "0";
                }
                clock += day + " ";

                if (hh < 10)
                    clock += "0";
                clock += hh + ":";
                if (mm < 10)
                    clock += "0";
                clock += mm + ":";
                if (ss < 10)
                    clock += "0";
                clock += ss;
            }
                break;
            case "yyyyMMddHHmmss": {
                clock = year;
                if (month < 10)
                    clock += "0";
                clock += month;
                if (day < 10) {
                    clock += "0";
                }
                clock += day;

                if (hh < 10)
                    clock += "0";
                clock += hh;
                if (mm < 10)
                    clock += "0";
                clock += mm;
                if (ss < 10)
                    clock += "0";
                clock += ss;
            }
                break;
            case "MMddHHmm": {
                clock = "";
                var nowdata = new Date();
                var nowYear = nowdata.getFullYear();
                var nowMonth = nowdata.getMonth() + 1;
                var nowDay = nowdata.getDate();
                var nowdatastr = nowYear + nowMonth + nowDay;
                var datastr = year + month + day;
                if (nowdatastr == datastr) {
                    clock += hh + ":";
                    clock += mm;
                }
                else {
                    clock += month + "-";
                    clock += day + " ";
                    clock += hh + ":";
                    clock += mm;
                }
            }
                break;
        }

        return clock;

    },
    //获取上一周的日期，从周一到周日
    getLastWeekDate: function () {
        var now = new Date();
        //var week = new Array();
        var currentWeek = now.getDay();

        if (currentWeek == 0) {
            currentWeek = 7;
        }
        var monday = now.getTime() - (currentWeek + 6) * 24 * 60 * 60 * 1000; //星期一
        var tuesday = now.getTime() - (currentWeek + 5) * 24 * 60 * 60 * 1000; //星期二
        var wednesday = now.getTime() - (currentWeek + 4) * 24 * 60 * 60 * 1000; //星期三
        var thursday = now.getTime() - (currentWeek + 3) * 24 * 60 * 60 * 1000; //星期四
        var friday = now.getTime() - (currentWeek + 2) * 24 * 60 * 60 * 1000; //星期五
        var saturday = now.getTime() - (currentWeek + 1) * 24 * 60 * 60 * 1000; //星期六
        var sunday = now.getTime() - (currentWeek) * 24 * 60 * 60 * 1000;   //星期日

        //week = weektoday(monday, tuesday, wednesday, thursday, friday, saturday, sunday);

        return {
            monday: monday, sunday: sunday
        }

    },
    setCookie: function (name, value, t) {  //设置cookie，默认保存30天
        var Days = 30;
        var exp = new Date();
        if (t) {
            exp.setTime(exp.getTime() + parseInt(t) * 24 * 60 * 60 * 1000);
        } else {
            exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
        }
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
    },
    getCookie: function (name) {//获取cookie
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    },
    delCookie: function (name) { //删除cookie
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = ComFunJS.getCookie(name);
        if (cval != null) {
            document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=/;";
        }
    },
    saveToken: function (obj) {
        if (ComFunJS.getCookie("txcb3cd78e191e21")) {
            ComFunJS.delCookie("txcb3cd78e191e21");
        }
        ComFunJS.setCookie("txcb3cd78e191e21", obj, 30);
    },
    //获取Token
    getToken: function () {
        return ComFunJS.getCookie("txcb3cd78e191e21");
    },
    delToken: function () {
        ComFunJS.delCookie("txcb3cd78e191e21");
    },
    isLogin: function (r) { //r:true时转到登录页
        var islogin = false;
        if (ComFunJS.getToken()) {
            islogin = true;
        }

        if (r && !islogin) {//返回登录页面
            var url = encodeURIComponent(window.location.toString());
            window.location = "/mobile/login.html?returnurl=" + url;
        }

        return islogin;

        //if (!ComFunJS.getToken()) {
        //    var url = encodeURIComponent(window.location.toString());
        //    window.location = "/mobile/login.html?returnurl=" + url;
        //    //var code = ComFunJS.getQueryString("code");
        //    //if (code) {
        //    //    $.ajax({
        //    //        type: "GET",
        //    //        url: "/weixin/code/" + code,
        //    //        dataType: "json",
        //    //        async: true,
        //    //        success: function (data, textStatus) {
        //    //            if (data.error == "") {
        //    //                ComFunJS.saveToken(data.result);
        //    //            }
        //    //        },
        //    //        error: function (XMLHttpRequest, textStatus, errorThrown) {

        //    //        }
        //    //    })

        //    //} else {
        //    //    var url = encodeURIComponent(window.location.toString());
        //    //    window.location = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx56652205b133df19&redirect_uri=" + url + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        //    //}
        //}
    },
    //layer控件扩展
    //警告
    showAlert: function (msg) {
        var msg = msg || "出错了";
        layer.open({
            content: msg,
            style: 'color:red; border:none;',
            btn: '确定'
        })
    },
    //信息提示，默认2秒消失
    showMsg: function (msg,time) {
        var msg = msg || "提示";
        var time = time || 2;
        layer.open({
            content: msg,
            anim: 'up',
            style: 'width:90%',
            skin: 'msg',
            time: time
        });
    },
    //确认
    showConfirm: function (msg, yes, no) {
        var lyindex = layer.open({
            content: msg,
            btn: ['确认', '取消'],
            yes: function (index) {
                layer.close(lyindex);
                return yes && yes.call(this);
            },
            no: function (index) {
                return no && no.call(this);
            }
        });

    },
    //底部弹出确认
    showConfirm2: function (msg, yes, btn1, no, btn2) {
        var btn1 = btn1 || "确认";
        var btn2 = btn2 || "取消";
        var lyindex = layer.open({
            content: msg,
            btn: [btn1, btn2],
            skin: 'footer',
            yes: function (index) {
                layer.close(lyindex);
                return yes && yes.call(this);
            },
            no: function (index) {
                return no && no.call(this);
            }
        });
    },
    //加载中
    showLoading: function (msg) {
        var msg = msg || "玩命加载中";
        layer.open({
            type: 2,
            content: msg,
            shadeClose: false,
            shade: 'background-color: rgba(0,0,0,.3)'
        })
    },
    //关闭layer
    close: function (lyindex) {
        if (lyindex) {
            layer.close(lyindex);
        } else {
            setTimeout("layer.closeAll()", 1500);
        }
    },
    showValidSMS: function (tel, type, callback) {
        $.getJSON(ComFunJS.APIURL("Verification/Validate/" + type + "/" + tel), function (r) {
            if (r.error == "") {
                ComFunJS.showMsg("请输入手机收到的验证码");
                return callback.call(this);
            }
            else {
                ComFunJS.showMsg(r.error);
            }
        });
    },
    //显示html信息
    showHtml: function (html, callback) {
        var title = title || "信息";
        var height = height || "200";

        layer.open({
            type: 1,
            content: html,
            shadeClose: true,
            style: 'width:100%;height:' + height + 'px;background-color:none;',
            anim: 'up',
            success: function (layero) {
                if (callback) {
                    return callbact.call(this, layero);
                }
            }

        });
    },
    //layer控件扩展
    //PC
    winShowForm: function (url, title, width, height) {
        var title = title || "信息";
        var width = width || $(window).width() * 0.9;
        var height = height || $(window).height() * 0.8;
        if (height < 600) {
            height = 600;
        } else if (height > 1000) {
            height = 1000;
        }
        layer.open({
            title: title,
            type: 2,
            area: [width + 'px', height + 'px'],
            maxmin: true,
            scrollbar: false,
            content: url //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
        });

    },
    winShowAlert: function (msg) {
        var msg = msg || "出错了";
        layer.alert(msg, { icon: 5 });
    },
    winShowMsg: function (msg) {
        var msg = msg || "提示";
        layer.msg(msg);
    },
    winShowConfirm: function (msg, yes, no) {
        layer.confirm(msg, {
            btn: ['确认', '取消'], //按钮
            shade: false //不显示遮罩
        }, function () {
            layer.closeAll('dialog');
            return yes && yes.call(this);
        }, function () {
            return no && no.call(this);
        })
    },
    winShowAudit: function (msg, yes, no) {
        layer.confirm(msg, {
            btn: ["通过", "拒绝", "取消"],
            shade: false
        }, function () {
            layer.closeAll("dialog");
            return yes && yes.call(this);
        }, function () {
            return no && no.call(this);
        })
    },
    winShowFormBtn: function (title, url, width, height, btcallbact) {
        var width = width || $(window).width() - 300;
        var height = height || $(window).height();
        var optionwin = {
            type: 2,
            fix: true, //不固定
            area: [width + 'px', height + 'px'],
            maxmin: true,
            content: url,
            title: title,
            shadeClose: false,
            success: function (layero, index) {
                if ($(layero).find(".successfoot").length == 0) {
                    var footdv = $('<div class="layui-layer-title successfoot" style="border-bottom-width: 1px; padding: 0 20px 0 10px;margin-top: -3px;height:50px"></div>');
                    var btnConfirm = $("<a href='#' class='sui-btn btn-xlarge btn-success' style='float:right; margin-top: 10px;'><i class='fa fa-spinner fa-spin' style='display:none'></i> 确   认</a>");
                    var btnCancel = $("<a href='#' class='sui-btn btn-xlarge' style='float:right; margin-top: 10px;margin-right: 10px;'>取  消</a>");
                    var msg = $("<input type='hidden' class='r_data' >");

                    btnConfirm.appendTo(footdv).bind('click', function () {
                        return btcallbact.call(this, layero, index, btnConfirm);
                    })
                    btnCancel.appendTo(footdv).bind('click', function () {
                        layer.close(index)
                    })
                    $(layero).append(footdv).append(msg);

                    try {
                    } catch (e) { }
                }

            }
        }
        layer.open(optionwin);
    },
    fileUpload: function (file, callback) {
        YDUI.dialog.loading.open('正在上传...');
        if ($(file)[0].files.length > 0) {
            lrz($(file)[0].files[0], { fieldName: "upFile" }).then(function (rst) {
                rst.formData.append('fileLen', rst.fileLen);
                $.ajax({
                    url: "/file/uploadfile",
                    type: "POST",
                    data: rst.formData,
                    contentType: false,
                    processData: false,
                    success: function (r) {
                        if (r.error == "") {
                            return callback && callback.call(this, r.result);
                        } else {
                            YDUI.dialog.toast(r.error, 'error','3000', function () {
                               
                            });
                        }
                    },
                    complete: function (xhr, ts) { }
                })
            }).always(function () {
                YDUI.dialog.loading.close();
            });
        }
    },
    //fileUpload: function (callback) {
    //    ComFunJS.winShowFormBtn("请选择文件", "/admin/js/fileupload.html", "500", "400", function (layero, index, btdom) {
    //        var iframeWin = layero.find('iframe')[0];
    //        var data = iframeWin.contentWindow.getFileData();
    //        if (data && data.length > 0) {
    //            $.post("/file/addfile", {
    //                P1: JSON.stringify(data)
    //            }, function (r) {
    //                if (r.error == "") {

    //                    layer.close(index);
    //                    return callback.call(this, r.result);
    //                }
    //            })
    //        } else {
    //            layer.close(index);
    //        }

    //    })
    //},
    initForm: function () {
        //if ($(".bw_ueditor").length > 0) {
        //    $(".bw_ueditor").each(function () {
        //        var input = $(this);
        //        var ubid = $(this).attr("id");
        //        var um = UM.getEditor(ubid);
        //        if ($(this).attr("umheight")) {
        //            um.setHeight($(this).attr("umheight"));
        //        } else {
        //            um.setHeight("120")
        //        }
        //        um.ready(function () {
        //            if (input.val() != "") {
        //                //需要ready后执行，否则可能报错
        //                um.setContent(input.val());
        //            }
        //            if ($(this).hasClass("focus")) {
        //                um.focus()
        //            }


        //        })
        //        um.addListener('contentChange', function () {
        //            input.val(UM.getEditor(ubid).getContent());
        //        })

        //    })
        //}
    },
    GetDomain: function () {
        var host = window.location.host;
        if (host.lastIndexOf("/") == -1) {
            host += "/";
        }
        return "http://" + host;
    },
    //微信JSAPI授权
    GETWXJSSDK: function (wxtitle, wxdesp, imgUrl, urllink, callback) {
        if (ComFunJS.isWeiXin()) {
            var title = document.title;
            if (wxtitle) {
                title = wxtitle;
            }
            var desp = title;
            if (wxdesp) {
                desp = wxdesp;
            }
            if (imgUrl) {
                imgUrl = ComFunJS.FilePath(imgUrl, "/200/200");
            }
            var link = window.location.href.split('#')[0];
            if (urllink) {
                link = urllink;
            }
            $.post("/weixin/jsapi", { url: encodeURIComponent(window.location.href.split('#')[0]) }, function (r) {
                if (r.error == "") {

                    wx.config({
                        debug: false,
                        appId: r.result.appId,
                        timestamp: r.result.timestamp,
                        nonceStr: r.result.noncestr,
                        signature: r.result.signature,
                        jsApiList: [
                          'checkJsApi',
                          'onMenuShareTimeline',
                          'onMenuShareAppMessage',
                          'onMenuShareQQ',
                          'onMenuShareWeibo',
                          'hideMenuItems',
                          'showMenuItems',
                          'hideAllNonBaseMenuItem',
                          'showAllNonBaseMenuItem',
                          'translateVoice',
                          'startRecord',
                          'stopRecord',
                          'onRecordEnd',
                          'playVoice',
                          'pauseVoice',
                          'stopVoice',
                          'uploadVoice',
                          'downloadVoice',
                          'chooseImage',
                          'previewImage',
                          'uploadImage',
                          'downloadImage',
                          'getNetworkType',
                          'openLocation',
                          'getLocation',
                          'hideOptionMenu',
                          'showOptionMenu',
                          'closeWindow',
                          'scanQRCode',
                          'chooseWXPay',
                          'openProductSpecificView',
                          'addCard',
                          'chooseCard',
                          'openCard'
                        ]
                    })


                    wx.ready(function () {

                        //分享给朋友分享到朋友圈
                        wx.onMenuShareTimeline({
                            title: title, // 分享标题
                            link: link, // 分享链接
                            imgUrl: imgUrl, // 分享图标
                            success: function () {
                                return callback && callback.call(this);
                                // 用户确认分享后执行的回调函数
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                            }
                        });

                        //分享给朋友
                        wx.onMenuShareAppMessage({
                            title: title, // 分享标题
                            desc: desp, // 分享描述
                            link: link, // 分享链接
                            imgUrl: imgUrl, // 分享图标
                            type: '', // 分享类型,music、video或link，不填默认为link
                            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                            success: function () {
                                return callback && callback.call(this);
                                // 用户确认分享后执行的回调函数
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                            }
                        });

                        //分享到QQ
                        wx.onMenuShareQQ({
                            title: title, // 分享标题
                            desc: desp, // 分享描述
                            link: link, // 分享链接
                            imgUrl: imgUrl, // 分享图标
                            success: function () {
                                return callback && callback.call(this);
                                // 用户确认分享后执行的回调函数
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                            }
                        });

                        //分享到腾讯微博
                        wx.onMenuShareWeibo({
                            title: title, // 分享标题
                            desc: title, // 分享描述
                            link: link, // 分享链接
                            imgUrl: imgUrl, // 分享图标
                            success: function () {
                                return callback && callback.call(this);
                                // 用户确认分享后执行的回调函数
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                            }
                        });

                        //分享到QQ空间
                        wx.onMenuShareQZone({
                            title: title, // 分享标题
                            desc: desp, // 分享描述
                            link: link, // 分享链接
                            imgUrl: imgUrl, // 分享图标
                            success: function () {
                                return callback && callback.call(this);
                                // 用户确认分享后执行的回调函数
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                            }
                        });

                    })
                    wx.error(function (res) {
                    })

                }

            })
        }


    },
    //规则验证
    regMatch: function (type, value) {
        var reg;
        switch (type) {
            case "tel":
                {
                    reg = /^1[3|4|5|8|7]\d{9}$/;
                }
                break;
        }
        return reg.test(value);

    },
    toUtf8: function (str) {
        var out, i, len, c;
        out = "";
        len = str.length;
        for (i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                out += str.charAt(i);
            } else if (c > 0x07FF) {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } else {
                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
        }
        return out;
    },
    guid: function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    },
    getMS: function (time) {   //秒装换   分:秒
        return time;
        //if (!time) {
        //    return;
        //}
        //var h = 0,
        //m = 0,
        //s = 0,
        //_h = '00',
        //_m = '00',
        //_s = '00';
        //h = Math.floor(time / 3600);
        //time = Math.floor(time % 3600);
        //m = Math.floor(time / 60);
        //s = Math.floor(time % 60);
        //_s = s < 10 ? '0' + s : s + '';
        //_m = m < 10 ? '0' + m : m + '';
        //_h = h < 10 ? '0' + h : h + '';
        //if (_h == '00') {
        //    return _m + ":" + _s;
        //}
        //else {
        //    return _h + ":" + _m + ":" + _s;
        //}
    },
    strToIds: function (text) {
        var ids = [];
        if (text) {
            text.split(',').forEach(function (item, index) {
                ids.push({
                    "ID": "" + item + ""
                });
            })
        }
        return ids;
    },
    goBack: function (url) {//1.返回上一页，无法返回时返回到url
        if ((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0)) { // IE
            if (history.length > 0) {
                window.history.go(-1);
            } else {
                window.location.href = url;
            }
        } else { //非IE浏览器
            if (navigator.userAgent.indexOf('Firefox') >= 0 ||
                navigator.userAgent.indexOf('Opera') >= 0 ||
                navigator.userAgent.indexOf('Safari') >= 0 ||
                navigator.userAgent.indexOf('Chrome') >= 0 ||
                navigator.userAgent.indexOf('WebKit') >= 0) {
                if (window.history.length > 1) {
                    window.history.go(-1);
                } else {
                    window.location.href = url;
                }
            } else { //未知的浏览器
                window.history.go(-1);
            }
        }
    },
    isWeiXin: function () {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            return true;
        } else {
            return false;
        }
    }
};



//购物车
var cart = {
    setParam: function (name, value) {
        localStorage.setItem(name, value);
    },
    getParam: function (name) {
        return localStorage.getItem(name);
    },
    removeParam: function (name) {
        if (localStorage.getItem(name)) {
            localStorage.removeItem(name);
        }
    },
    productModel:function()
    {
        return {
            ID: 0,
            Title: "",
            Price1: 0,
            Price2: 0,
            Price3: 0,
            Price4: 0,
            Price5: 0,
            Qty: 1,
            ImgUrl: "",
            ISSel: true,
            Fee: 0,
            TuanQty: 1,
            Status: 1  //状态，1：上架,0下架
        }
    },
    addProduct: function (product) {
        if (product) {
            var shopcart = cart.getParam("shopcart");
            var productlist = [];
            if (shopcart) {
                productlist = JSON.parse(shopcart).productlist;
            }
            var isFind = false;
            for (var i in productlist) {
                if (productlist[i].ID == product.ID) {
                    productlist[i].Qty = parseInt(productlist[i].Qty) + parseInt(product.Qty);
                    isFind = true;
                    break;
                }
            }
            if(!isFind)
            {
                var cproduct = cart.productModel();
                if (product.ID) {
                    cproduct.ID = product.ID;
                }
                if (product.Title) {
                    cproduct.Title = product.Title;
                }
                if (product.Price1) {
                    cproduct.Price1 = product.Price1;
                }
                if (product.Price2) {
                    cproduct.Price2 = product.Price2;
                }
                if (product.Price3) {
                    cproduct.Price3 = product.Price3
                }
                if (product.Qty) {
                    cproduct.Qty = product.Qty;
                }
                if (product.Fee) {
                    cproduct.Fee = product.Fee;
                }

                productlist.push(cproduct);
            }
            cart.setParam("shopcart", JSON.stringify({ "productlist": productlist }));
        }

    },
    getProduct: function (ID) {
        var shopcart = cart.getParam("shopcart");
        if (shopcart) {
            var productlist = JSON.parse(shopcart).productlist;
            if (ID) {
                for (var i in productlist) {
                    if (productlist[i].ID == ID) {
                        return productlist[i];
                    }
                }
            } else {
                return productlist;
            }
        }
    },
    getProductSel: function () {
        var shopcart = cart.getParam("shopcart");
        if (shopcart) {
            var list = [];
            var productlist = JSON.parse(shopcart).productlist;
            for (var i in productlist) {
                if (productlist[i].ISSel) {
                    list.push(productlist[i]);
                }
            }
            return list;
        }
    },
    getProductQty: function (isel) {
        var Qty = 0;
        var Price1 = 0.00;
        var Price2 = 0.00;
        var Price3 = 0.00;
        var Fee = 0;
        var shopcart = cart.getParam("shopcart");
        if (shopcart) {
            var productlist = JSON.parse(shopcart).productlist;
            if (isel && isel == true) {
                for (var i in productlist) {
                    if (productlist[i].ISSel) {
                        qty += parseInt(productlist[i].Qty);
                        price1 += parseInt(productlist[i].qty) * productlist[i].Price1;
                        price2 += parseInt(productlist[i].qty) * productlist[i].Price2;
                        price3 += parseInt(productlist[i].qty) * productlist[i].Price3;

                        Fee += productlist[i].Fee;
                    }
                }
            } else {
                for (var i in productlist) {
                    Qty += parseInt(productlist[i].Qty);
                    Price1 += parseInt(productlist[i].Qty) * productlist[i].Price1;
                    Price2 += parseInt(productlist[i].Qty) * productlist[i].Price2;
                    Price3 += parseInt(productlist[i].Qty) * productlist[i].Price3;

                    Fee += productlist[i].Fee;
                }
            }
            
        }
        return { "Qty": Qty, "Price1": Price1.toFixed(2), "Price2": Price2.toFixed(2), "Price3": Price3.toFixed(2), "Fee": Fee.toFixed(0) };
    },
    updateProductQty: function (ID,Qty) {
        var shopcart = cart.getParam("shopcart");
        if (shopcart && ID) {
            var productlist = JSON.parse(shopcart).productlist;
            for (var i in productlist) {
                if (productlist[i].ID == ID) {
                    productlist[i].Qty = Qty;
                    break;
                }
            }
            cart.setParam("shopcart", JSON.stringify({ "productlist": productlist }));
        }

    },
    updateProductSel: function (ID, ISSel) {
        var shopcart = cart.getParam("shopcart");
        if (shopcart && ID) {
            var productlist = JSON.parse(shopcart).productlist;
            for (var i in productlist) {
                if (productlist[i].ID == ID) {
                    productlist[i].ISSel = ISSel;
                    break;
                }
            }
            cart.setParam("shopcart", JSON.stringify({ "productlist": productlist }));
        }

    },
    updateProductSelAll: function (ISSel) {
        var shopcart = cart.getParam("shopcart");
        if (shopcart) {
            var productlist = JSON.parse(shopcart).productlist;
            for (var i in productlist) {
                productlist[i].ISSel = ISSel;
            }
        }
        cart.setParam("shopcart", JSON.stringify({ "productlist": productlist }));
    },
    delSelProduct: function () {
        var shopcart = cart.getParam("shopcart");
        if (shopcart) {
            var list = [];
            var productlist = JSON.parse(shopcart).productlist;
            for (var i in productlist) {
                if (!productlist[i].ISSel) {
                    list.push(productlist[i]);
                }
            }
            cart.setParam("shopcart", JSON.stringify({ "productlist": list }));
        }
    },
    delProduct: function (ID) {
        var flag = false;
        var shopcart = cart.getParam("shopcart");
        if (shopcart) {
            if (ID) {
                var productlist = JSON.parse(shopcart).productlist;
                var index = 0;
                for (var i = 0; i < productlist.length; i++) {
                    if (productlist[i].ID == ID) {
                        index = i;
                        break;
                    }
                }
                productlist.splice(index, 1);
                cart.setParam("shopcart", JSON.stringify({ "productlist": productlist }));
            } else {
                cart.removeParam("shopcart");
            }
            flag = true;
        }
        return flag;
    }


};



///<abbr class="timeago" title="2012-11-28T11:17:00Z"></abbr>
///   $(".timeago").timeago();     jQuery.timeago("2012-12-09");            //=> "1天前" 
;(function ($) {
    $.timeago = function (timestamp) {
        if (timestamp instanceof Date) {
            return inWords(timestamp);
        } else if (typeof timestamp === "string") {
            return inWords($.timeago.parse(timestamp));
        } else if (typeof timestamp === "number") {
            return inWords(new Date(timestamp));
        } else {
            return inWords($.timeago.datetime(timestamp));
        }
    };
    var $t = $.timeago;

    $.extend($.timeago, {
        settings: {
            refreshMillis: 60000,
            allowFuture: false,
            strings: {
                prefixAgo: null,
                prefixFromNow: "从现在开始",
                suffixAgo: "前",
                suffixFromNow: null,
                seconds: "不到 1 分钟",
                minute: "大约 1 分钟",
                minutes: "%d 分钟",
                hour: "大约 1 小时",
                hours: "大约 %d 小时",
                day: "1 天",
                days: "%d 天",
                month: "大约 1 个月",
                months: "%d 个月",
                year: "大约 1 年",
                years: "%d 年",
                numbers: [],
                wordSeparator: ""
            }
        },
        inWords: function (distanceMillis) {
            var $l = this.settings.strings;
            var prefix = $l.prefixAgo;
            var suffix = $l.suffixAgo;
            if (this.settings.allowFuture) {
                if (distanceMillis < 0) {
                    prefix = $l.prefixFromNow;
                    suffix = $l.suffixFromNow;
                }
            }

            var seconds = Math.abs(distanceMillis) / 1000;
            var minutes = seconds / 60;
            var hours = minutes / 60;
            var days = hours / 24;
            var years = days / 365;

            function substitute(stringOrFunction, number) {
                var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction;
                var value = ($l.numbers && $l.numbers[number]) || number;
                return string.replace(/%d/i, value);
            }

            var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
              seconds < 90 && substitute($l.minute, 1) ||
              minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
              minutes < 90 && substitute($l.hour, 1) ||
              hours < 24 && substitute($l.hours, Math.round(hours)) ||
              hours < 42 && substitute($l.day, 1) ||
              days < 30 && substitute($l.days, Math.round(days)) ||
              days < 45 && substitute($l.month, 1) ||
              days < 365 && substitute($l.months, Math.round(days / 30)) ||
              years < 1.5 && substitute($l.year, 1) ||
              substitute($l.years, Math.round(years));

            var separator = $l.wordSeparator === undefined ? " " : $l.wordSeparator;
            return $.trim([prefix, words, suffix].join(separator));
        },
        parse: function (iso8601) {
            var s = $.trim(iso8601);
            s = s.replace(/\.\d+/, ""); // remove milliseconds
            s = s.replace(/-/, "/").replace(/-/, "/");
            s = s.replace(/T/, " ").replace(/Z/, " UTC");
            s = s.replace(/([\+\-]\d\d)\:?(\d\d)/, " $1$2"); // -04:00 -> -0400
            return new Date(s);
        },
        datetime: function (elem) {
            var iso8601 = $t.isTime(elem) ? $(elem).attr("datetime") : $(elem).attr("title");
            return $t.parse(iso8601);
        },
        isTime: function (elem) {
            // jQuery's `is()` doesn't play well with HTML5 in IE
            return $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
        }
    });

    $.fn.timeago = function () {
        var self = this;
        self.each(refresh);

        var $s = $t.settings;
        if ($s.refreshMillis > 0) {
            setInterval(function () { self.each(refresh); }, $s.refreshMillis);
        }
        return self;
    };

    function refresh() {
        var data = prepareData(this);
        if (!isNaN(data.datetime)) {
            $(this).text(inWords(data.datetime));
        }
        return this;
    }

    function prepareData(element) {
        element = $(element);
        if (!element.data("timeago")) {
            element.data("timeago", { datetime: $t.datetime(element) });
            var text = $.trim(element.text());
            if (text.length > 0 && !($t.isTime(element) && element.attr("title"))) {
                element.attr("title", text);
            }
        }
        return element.data("timeago");
    }

    function inWords(date) {
        return $t.inWords(distance(date));
    }

    function distance(date) {
        return (new Date().getTime() - date.getTime());
    }

    // fix for IE6 suckage
    document.createElement("abbr");
    document.createElement("time");
}(window.Zepto || window.jQuery));


//重写ajax方法
; (function ($) {

    //首先备份下jquery的ajax方法  
    var _ajax = $.ajax;

    //重写jquery的ajax方法  
    $.ajax = function (opt) {
        //备份opt中error和success方法  
        var fn = {
            error: function (XMLHttpRequest, textStatus, errorThrown) { },
            success: function (data, textStatus) { }
        }
        if (opt.error) {
            fn.error = opt.error;
        }
        if (opt.success) {
            fn.success = opt.success;
        }

        //扩展增强处理  
        var _opt = $.extend(opt, {
            headers: {
                Authorization: ComFunJS.getToken()
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //错误方法增强处理  
                fn.error(XMLHttpRequest, textStatus, errorThrown);
            },
            success: function (data, textStatus) {
                //成功回调方法增强处理  
                fn.success(data, textStatus);
            },
            beforeSend: function (XHR) {
                //提交前回调方法  
                //$('body').append("<div id='ajaxInfo' style=''>正在加载,请稍后...</div>");
            },
            complete: function (XHR, TS) {
                //请求完成后回调函数 (请求成功或失败之后均调用)。  
                //$("#ajaxInfo").remove();;
            }
        });
        return _ajax(_opt);
    };
})(window.Zepto || window.jQuery);
